import { useState, useRef, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Label } from '@/components/ui/label'
import { Input } from '@/components/ui/input'
import { Slider } from '@/components/ui/slider'
import { Switch } from '@/components/ui/switch'
import { 
  Upload, 
  Scissors, 
  Play, 
  Pause, 
  Volume2, 
  VolumeX,
  Loader2,
  FileAudio,
  Download,
  Trash2,
  CheckCircle2,
  Clock,
  FileVolume,
  FolderOpen
} from 'lucide-react'
import { Title } from '@/components/common/Title'
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@/components/ui/select'
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group'
import { IPC_CHANNELS } from 'shared/ipcChannels'

interface AudioFile {
  name: string
  path: string
  duration: number // 秒
  size: number // 字节
}

interface SplitResult {
  name: string
  path: string
  duration: number
  size: number
}

type SplitMode = 'duration' | 'segments' | 'silence'

export default function AudioSplit() {
  // 音频文件状态
  const [audioFile, setAudioFile] = useState<AudioFile | null>(null)
  const [audioUrl, setAudioUrl] = useState<string>('')
  
  // 播放器状态
  const [isPlaying, setIsPlaying] = useState(false)
  const [currentTime, setCurrentTime] = useState(0)
  const [volume, setVolume] = useState([80])
  const [isMuted, setIsMuted] = useState(false)
  const audioRef = useRef<HTMLAudioElement>(null)
  const [playingSegmentPath, setPlayingSegmentPath] = useState<string | null>(null) // 当前播放的片段路径
  
  // 分割配置
  const [splitMode, setSplitMode] = useState<SplitMode>('duration')
  const [segmentDuration, setSegmentDuration] = useState(300) // 秒（默认5分钟）
  const [durationUnit, setDurationUnit] = useState<'seconds' | 'minutes'>('minutes')
  const [segmentCount, setSegmentCount] = useState(10)
  const [silenceThreshold, setSilenceThreshold] = useState(-30) // dB
  const [minSilenceDuration, setMinSilenceDuration] = useState(1) // 秒
  const [outputFormat, setOutputFormat] = useState('mp3')
  const [outputQuality, setOutputQuality] = useState('high')
  const [filenamePrefix, setFilenamePrefix] = useState('segment')
  const [addTimestamp, setAddTimestamp] = useState(true)
  const [outputFolder, setOutputFolder] = useState(() => {
    // 从 localStorage 读取上次使用的输出文件夹
    const saved = localStorage.getItem('audioSplit:outputFolder')
    return saved || ''
  })
  
  // 处理状态
  const [isProcessing, setIsProcessing] = useState(false)
  const [progress, setProgress] = useState(0)
  const [totalSegments, setTotalSegments] = useState<number | null>(null) // 实际片段总数
  const [currentSegment, setCurrentSegment] = useState(0) // 当前处理的片段编号
  const [splitResults, setSplitResults] = useState<SplitResult[]>([])
  
  // 格式化时间
  const formatTime = (seconds: number) => {
    const mins = Math.floor(seconds / 60)
    const secs = Math.floor(seconds % 60)
    return `${mins}:${secs.toString().padStart(2, '0')}`
  }
  
  // 格式化文件大小
  const formatSize = (bytes: number) => {
    if (bytes < 1024) return bytes + ' B'
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(2) + ' KB'
    return (bytes / (1024 * 1024)).toFixed(2) + ' MB'
  }
  
  // 播放/暂停切换（主音频文件）
  const togglePlay = () => {
    if (audioRef.current) {
      if (isPlaying && !playingSegmentPath) {
        audioRef.current.pause()
      } else if (!playingSegmentPath) {
        audioRef.current.play()
      }
      setIsPlaying(!isPlaying && !playingSegmentPath)
    }
  }
  
  // 播放分割片段
  const playSegment = (segmentPath: string) => {
    // 如果正在播放同一个片段，则暂停
    if (playingSegmentPath === segmentPath && isPlaying) {
      if (audioRef.current) {
        audioRef.current.pause()
        // 注意：不立即清除 playingSegmentPath，以便后续可以恢复播放
      }
      return
    }
    
    // 如果已经暂停了同一个片段，则恢复播放
    if (playingSegmentPath === segmentPath && !isPlaying) {
      if (audioRef.current) {
        audioRef.current.play().catch(err => {
          console.error('恢复播放失败:', err)
          alert('恢复播放失败')
        })
      }
      return
    }
    
    // 如果正在播放其他片段，先停止
    if (playingSegmentPath && playingSegmentPath !== segmentPath) {
      if (audioRef.current) {
        audioRef.current.pause()
        audioRef.current = null
      }
      setIsPlaying(false)
      setPlayingSegmentPath(null)
    }
    
    // 停止主音频播放（如果正在播放）
    if (audioRef.current && audioUrl && !playingSegmentPath) {
      audioRef.current.pause()
      setIsPlaying(false)
    }
    
    // 转换路径为 file:// URL
    const normalizedPath = segmentPath.replace(/\\/g, '/')
    const fileUrl = normalizedPath.startsWith('/') 
      ? `file://${normalizedPath}` 
      : `file:///${normalizedPath}`
    
    // 创建新的音频元素用于播放片段
    const segmentAudio = new Audio(fileUrl)
    
    // 设置音量和静音状态
    segmentAudio.volume = volume[0] / 100
    segmentAudio.muted = isMuted
    
    // 播放事件监听器
    const handlePlay = () => {
      setIsPlaying(true)
      setPlayingSegmentPath(segmentPath)
    }
    
    // 暂停事件监听器（用户手动暂停时不清除 playingSegmentPath）
    const handlePause = () => {
      setIsPlaying(false)
      // 不清除 playingSegmentPath，以便可以恢复播放
    }
    
    // 时间更新监听器
    const handleTimeUpdate = () => {
      setCurrentTime(segmentAudio.currentTime)
    }
    
    // 播放结束监听器
    const handleEnded = () => {
      setIsPlaying(false)
      setPlayingSegmentPath(null)
      setCurrentTime(0)
      // 清理事件监听器
      segmentAudio.removeEventListener('play', handlePlay)
      segmentAudio.removeEventListener('pause', handlePause)
      segmentAudio.removeEventListener('timeupdate', handleTimeUpdate)
      segmentAudio.removeEventListener('ended', handleEnded)
      segmentAudio.removeEventListener('error', handleError)
    }
    
    // 错误监听器
    const handleError = (e: Event) => {
      console.error('播放音频片段失败:', e)
      alert('播放音频失败，请确保文件存在')
      setIsPlaying(false)
      setPlayingSegmentPath(null)
      setCurrentTime(0)
      // 清理事件监听器
      segmentAudio.removeEventListener('play', handlePlay)
      segmentAudio.removeEventListener('pause', handlePause)
      segmentAudio.removeEventListener('timeupdate', handleTimeUpdate)
      segmentAudio.removeEventListener('ended', handleEnded)
      segmentAudio.removeEventListener('error', handleError)
    }
    
    // 添加事件监听器
    segmentAudio.addEventListener('play', handlePlay)
    segmentAudio.addEventListener('pause', handlePause)
    segmentAudio.addEventListener('timeupdate', handleTimeUpdate)
    segmentAudio.addEventListener('ended', handleEnded)
    segmentAudio.addEventListener('error', handleError)
    
    segmentAudio.addEventListener('loadedmetadata', () => {
      segmentAudio.play().catch(err => {
        console.error('播放失败:', err)
        alert('播放音频失败，请确保文件存在')
        setIsPlaying(false)
        setPlayingSegmentPath(null)
      })
    })
    
    // 保存引用以便后续控制
    audioRef.current = segmentAudio
  }
  
  // 更新音量时也同步更新片段播放器的音量
  useEffect(() => {
    if (audioRef.current && playingSegmentPath) {
      audioRef.current.volume = volume[0] / 100
    }
  }, [volume, playingSegmentPath])
  
  // 更新静音状态时也同步更新片段播放器的静音状态
  useEffect(() => {
    if (audioRef.current && playingSegmentPath) {
      audioRef.current.muted = isMuted
    }
  }, [isMuted, playingSegmentPath])
  
  // 更新播放时间
  const handleTimeUpdate = () => {
    if (audioRef.current) {
      setCurrentTime(audioRef.current.currentTime)
    }
  }
  
  // 音量控制
  useEffect(() => {
    if (audioRef.current) {
      audioRef.current.volume = volume[0] / 100
    }
  }, [volume])
  
  // 静音控制
  useEffect(() => {
    if (audioRef.current) {
      audioRef.current.muted = isMuted
    }
  }, [isMuted])
  
  // 保存输出文件夹到 localStorage
  useEffect(() => {
    if (outputFolder) {
      localStorage.setItem('audioSplit:outputFolder', outputFolder)
    }
  }, [outputFolder])
  
  // 获取显示的时长值
  const getDisplayDuration = () => {
    if (durationUnit === 'minutes') {
      return Math.floor(segmentDuration / 60)
    }
    return segmentDuration
  }
  
  // 设置时长值（输入的值会根据当前单位转换为秒）
  const setDisplayDuration = (value: number) => {
    if (durationUnit === 'minutes') {
      setSegmentDuration(value * 60)
    } else {
      setSegmentDuration(value)
    }
  }
  
  // 切换单位
  const handleUnitChange = (newUnit: 'seconds' | 'minutes') => {
    setDurationUnit(newUnit)
  }
  
  // 获取预计分割数量
  const getEstimatedSegments = () => {
    if (!audioFile) return 0
    
    switch (splitMode) {
      case 'duration':
        return Math.ceil(audioFile.duration / segmentDuration)
      case 'segments':
        return segmentCount
      case 'silence':
        return '自动检测'
      default:
        return 0
    }
  }
  
  // 选择输出文件夹
  const selectOutputFolder = async () => {
    try {
      const result = await window.ipcRenderer.invoke('dialog:openFile', {
        properties: ['openDirectory']
      }) as { canceled: boolean; filePaths: string[] }
      
      if (!result.canceled && result.filePaths.length > 0) {
        const folderPath = result.filePaths[0]
        setOutputFolder(folderPath)
        console.log('选择的输出文件夹:', folderPath)
      }
    } catch (error) {
      console.error('选择文件夹失败:', error)
      alert('选择文件夹失败: ' + (error instanceof Error ? error.message : String(error)))
    }
  }
  
  // 监听分割进度
  useEffect(() => {
    const unsubscribe = window.ipcRenderer.on(
      IPC_CHANNELS.audio.splitProgress as any,
      (...args: unknown[]) => {
        const progressValue = args[0] as number
        setProgress(progressValue)
        
        // 根据进度和总片段数计算当前片段
        // 进度是完成度百分比，所以当前片段 = 已完成片段数 + 1（正在处理）
        if (totalSegments !== null && totalSegments > 0) {
          // 已完成片段数 = (进度百分比 / 100) * 总片段数
          const completed = Math.floor((progressValue / 100) * totalSegments)
          // 当前正在处理的片段 = 已完成片段数 + 1
          const current = Math.min(completed + 1, totalSegments)
          setCurrentSegment(current)
        }
      }
    )
    
    return () => {
      unsubscribe()
    }
  }, [totalSegments])
  
  // 音频分割处理
  const handleSplit = async () => {
    if (!audioFile) {
      alert('请先选择音频文件')
      return
    }
    
    if (!outputFolder) {
      alert('请先选择输出文件夹')
      return
    }
    
    setIsProcessing(true)
    setProgress(0)
    setSplitResults([])
    setCurrentSegment(0)
    
    // 计算预计片段数
    let estimatedTotal = 0
    if (splitMode === 'duration') {
      estimatedTotal = Math.ceil(audioFile.duration / segmentDuration)
    } else if (splitMode === 'segments') {
      estimatedTotal = segmentCount
    } else {
      // 静音检测模式，先用估算值
      estimatedTotal = Math.ceil(audioFile.duration / 10) // 粗略估算，每10秒一个片段
    }
    setTotalSegments(estimatedTotal)
    
    try {
      const config = {
        inputPath: audioFile.path,
        outputFolder: outputFolder,
        splitMode: splitMode,
        segmentDuration: splitMode === 'duration' ? segmentDuration : undefined,
        segmentCount: splitMode === 'segments' ? segmentCount : undefined,
        silenceThreshold: splitMode === 'silence' ? silenceThreshold : undefined,
        minSilenceDuration: splitMode === 'silence' ? minSilenceDuration : undefined,
        outputFormat: outputFormat,
        outputQuality: outputQuality,
        filenamePrefix: filenamePrefix || 'segment',
        addTimestamp: addTimestamp
      }
      
      const result = await window.ipcRenderer.invoke(
        IPC_CHANNELS.audio.splitAudio as any,
        config
      ) as {
        success: boolean
        results?: SplitResult[]
        message?: string
        error?: string
      }
      
      if (result.success && result.results) {
        setSplitResults(result.results)
        setProgress(100)
        setCurrentSegment(result.results.length)
        setTotalSegments(result.results.length)
        // 自动滚动到结果区域
        setTimeout(() => {
          const resultsElement = document.querySelector('[data-split-results]')
          if (resultsElement) {
            resultsElement.scrollIntoView({ behavior: 'smooth', block: 'start' })
          }
        }, 100)
      } else {
        alert(`分割失败: ${result.error || '未知错误'}`)
        setProgress(0)
        setTotalSegments(null)
        setCurrentSegment(0)
      }
    } catch (error) {
      console.error('分割音频失败:', error)
      alert('分割失败: ' + (error instanceof Error ? error.message : String(error)))
      setProgress(0)
      setTotalSegments(null)
      setCurrentSegment(0)
    } finally {
      setIsProcessing(false)
    }
  }
  
  // 打开输出文件夹
  const openOutputFolder = async () => {
    if (!outputFolder) return
    
    try {
      await window.ipcRenderer.invoke(IPC_CHANNELS.app.openPath as any, outputFolder)
    } catch (error) {
      console.error('打开文件夹失败:', error)
      alert('打开文件夹失败: ' + (error instanceof Error ? error.message : String(error)))
    }
  }

  return (
    <div className="container py-8 space-y-6">
      <div>
        <Title title="音频分割" description="将长音频文件分割成多个小片段" />
      </div>

      {/* 文件选择区域 */}
      <Card>
        <CardHeader>
          <CardTitle className="text-base">选择音频文件</CardTitle>
          <CardDescription>支持 MP3、WAV、M4A、AAC、OGG 等常见音频格式</CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          <div className="flex gap-2">
            <Button
              onClick={async () => {
                try {
                  const result = await window.ipcRenderer.invoke('dialog:openFile', {
                    filters: [
                      { 
                        name: '音频文件', 
                        extensions: ['mp3', 'wav', 'm4a', 'aac', 'ogg', 'flac', 'wma', 'opus'] 
                      }
                    ],
                    properties: ['openFile']
                  }) as { canceled: boolean; filePaths: string[] }
                  
                  if (!result.canceled && result.filePaths.length > 0) {
                    const filePath = result.filePaths[0]
                    console.log('选择的音频文件:', filePath)
                    
                    // 转换为 file:// URL 格式
                    const normalizedPath = filePath.replace(/\\/g, '/')
                    const fileUrl = normalizedPath.startsWith('/') 
                      ? `file://${normalizedPath}` 
                      : `file:///${normalizedPath}`
                    
                    console.log('音频 URL:', fileUrl)
                    setAudioUrl(fileUrl)
                    
                    // 创建临时音频元素获取元数据
                    const tempAudio = new Audio(fileUrl)
                    
                    const loadHandler = async () => {
                      const fileName = filePath.split(/[\\/]/).pop() || 'audio'
                      const duration = tempAudio.duration
                      
                      // 从主进程获取文件大小
                      let fileSize = 0
                      try {
                        const fileInfo = await window.ipcRenderer.invoke(IPC_CHANNELS.audio.getFileInfo as any, filePath) as { 
                          success: boolean
                          size?: number
                          error?: string
                        }
                        if (fileInfo.success && fileInfo.size) {
                          fileSize = fileInfo.size
                        }
                      } catch (err) {
                        console.warn('无法获取文件大小:', err)
                      }
                      
                      setAudioFile({
                        name: fileName,
                        path: filePath,
                        duration: duration,
                        size: fileSize
                      })
                      
                      setIsPlaying(false)
                      setSplitResults([])
                      
                      // 清理临时音频元素
                      tempAudio.removeEventListener('loadedmetadata', loadHandler)
                      tempAudio.removeEventListener('error', errorHandler)
                    }
                    
                    const errorHandler = (e: Event) => {
                      console.error('加载音频失败:', e)
                      alert('加载音频文件失败，请确保文件格式正确')
                      tempAudio.removeEventListener('loadedmetadata', loadHandler)
                      tempAudio.removeEventListener('error', errorHandler)
                    }
                    
                    tempAudio.addEventListener('loadedmetadata', loadHandler)
                    tempAudio.addEventListener('error', errorHandler)
                  }
                } catch (error) {
                  console.error('选择文件失败:', error)
                  alert('选择文件失败: ' + (error instanceof Error ? error.message : String(error)))
                }
              }}
              variant="default"
              className="flex-1 sm:flex-initial"
            >
              <Upload className="mr-2 h-4 w-4" />
              选择音频文件
            </Button>
            
            {audioFile && (
              <Button
                onClick={() => {
                  setAudioFile(null)
                  setAudioUrl('')
                  setSplitResults([])
                  setIsPlaying(false)
                  setCurrentTime(0)
                }}
                variant="outline"
                size="icon"
              >
                <Trash2 className="h-4 w-4" />
              </Button>
            )}
          </div>

          {audioFile && (
            <div className="p-4 bg-muted/50 rounded-lg space-y-3">
              <div className="flex items-start gap-3">
                <FileAudio className="h-5 w-5 text-primary mt-0.5" />
                <div className="flex-1 min-w-0">
                  <p className="font-medium truncate">{audioFile.name}</p>
                  <div className="flex flex-wrap gap-4 mt-2 text-sm text-muted-foreground">
                    <span className="flex items-center gap-1">
                      <Clock className="h-3 w-3" />
                      时长: {formatTime(audioFile.duration)}
                    </span>
                    <span className="flex items-center gap-1">
                      <FileVolume className="h-3 w-3" />
                      大小: {formatSize(audioFile.size)}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          )}
        </CardContent>
      </Card>

      {/* 音频播放器 */}
      {audioUrl && (
        <Card>
          <CardHeader>
            <CardTitle className="text-base">音频预览</CardTitle>
          </CardHeader>
          <CardContent className="space-y-4">
            <audio
              ref={audioRef}
              src={audioUrl}
              onTimeUpdate={handleTimeUpdate}
              onEnded={() => setIsPlaying(false)}
            />

            {/* 播放控制 */}
            <div className="flex items-center gap-4">
              <Button
                onClick={togglePlay}
                variant="outline"
                size="icon"
              >
                {isPlaying ? (
                  <Pause className="h-4 w-4" />
                ) : (
                  <Play className="h-4 w-4" />
                )}
              </Button>

              <div className="flex-1">
                <div className="flex justify-between text-xs text-muted-foreground mb-1">
                  <span>{formatTime(currentTime)}</span>
                  <span>{audioFile ? formatTime(audioFile.duration) : '0:00'}</span>
                </div>
                <div className="w-full bg-secondary rounded-full h-2">
                  <div 
                    className="bg-primary h-2 rounded-full transition-all"
                    style={{ 
                      width: audioFile ? `${(currentTime / audioFile.duration) * 100}%` : '0%' 
                    }}
                  />
                </div>
              </div>

              <Button
                variant="ghost"
                size="icon"
                onClick={() => setIsMuted(!isMuted)}
              >
                {isMuted || volume[0] === 0 ? (
                  <VolumeX className="h-4 w-4" />
                ) : (
                  <Volume2 className="h-4 w-4" />
                )}
              </Button>

              <div className="w-24">
                <Slider
                  value={volume}
                  onValueChange={setVolume}
                  max={100}
                  step={1}
                  disabled={isMuted}
                />
              </div>
            </div>
          </CardContent>
        </Card>
      )}

      {/* 分割配置 */}
      {audioFile && (
        <Card>
          <CardHeader>
            <CardTitle className="text-base">分割设置</CardTitle>
            <CardDescription>选择分割方式并配置参数</CardDescription>
          </CardHeader>
          <CardContent className="space-y-6">
            {/* 分割模式选择 */}
            <div className="space-y-3">
              <Label className="text-sm font-semibold">分割模式</Label>
              <RadioGroup value={splitMode} onValueChange={(v) => setSplitMode(v as SplitMode)}>
                <div className="flex items-center space-x-2 p-3 border rounded-lg hover:bg-muted/50 cursor-pointer transition-colors">
                  <RadioGroupItem value="duration" id="duration" />
                  <Label htmlFor="duration" className="flex-1 cursor-pointer">
                    <div className="font-medium">按时长分割</div>
                    <div className="text-xs text-muted-foreground">按固定时长将音频分割成多段</div>
                  </Label>
                </div>
                
                <div className="flex items-center space-x-2 p-3 border rounded-lg hover:bg-muted/50 cursor-pointer transition-colors">
                  <RadioGroupItem value="segments" id="segments" />
                  <Label htmlFor="segments" className="flex-1 cursor-pointer">
                    <div className="font-medium">按段数分割</div>
                    <div className="text-xs text-muted-foreground">将音频平均分割成指定段数</div>
                  </Label>
                </div>
                
                <div className="flex items-center space-x-2 p-3 border rounded-lg hover:bg-muted/50 cursor-pointer transition-colors">
                  <RadioGroupItem value="silence" id="silence" />
                  <Label htmlFor="silence" className="flex-1 cursor-pointer">
                    <div className="font-medium">静音检测分割</div>
                    <div className="text-xs text-muted-foreground">自动检测静音部分进行分割</div>
                  </Label>
                </div>
              </RadioGroup>
            </div>

            {/* 分割参数配置 */}
            <div className="space-y-4 p-4 bg-muted/30 rounded-lg">
              {splitMode === 'duration' && (
                <div className="space-y-3">
                  {/* 单位选择 */}
                  <div className="space-y-2">
                    <Label className="text-sm">时长单位</Label>
                    <div className="flex gap-2">
                      <Button
                        variant={durationUnit === 'seconds' ? 'default' : 'outline'}
                        size="sm"
                        onClick={() => handleUnitChange('seconds')}
                        className="flex-1"
                      >
                        秒
                      </Button>
                      <Button
                        variant={durationUnit === 'minutes' ? 'default' : 'outline'}
                        size="sm"
                        onClick={() => handleUnitChange('minutes')}
                        className="flex-1"
                      >
                        分钟
                      </Button>
                    </div>
                  </div>
                  
                  {/* 时长调节 */}
                  <div className="space-y-2">
                    <div className="flex items-center justify-between gap-2">
                      <Label className="text-sm">
                        每段时长
                      </Label>
                      <div className="flex items-center gap-2">
                        <Input
                          type="number"
                          value={getDisplayDuration()}
                          onChange={(e) => {
                            const value = parseInt(e.target.value) || 1
                            const max = durationUnit === 'seconds' ? 3600 : 60
                            setDisplayDuration(Math.min(Math.max(1, value), max))
                          }}
                          min={1}
                          max={durationUnit === 'seconds' ? 3600 : 60}
                          className="w-20 h-8 text-sm text-right"
                        />
                        <span className="text-sm text-muted-foreground min-w-[3rem]">
                          {durationUnit === 'seconds' ? '秒' : '分钟'}
                        </span>
                      </div>
                    </div>
                    <Slider
                      value={[getDisplayDuration()]}
                      onValueChange={([v]) => setDisplayDuration(v)}
                      min={1}
                      max={durationUnit === 'seconds' ? 3600 : 60}
                      step={durationUnit === 'seconds' ? 1 : 1}
                    />
                    <div className="flex justify-between text-xs text-muted-foreground">
                      <span>{durationUnit === 'seconds' ? '1秒' : '1分钟'}</span>
                      <span>{durationUnit === 'seconds' ? '3600秒 (1小时)' : '60分钟 (1小时)'}</span>
                    </div>
                  </div>
                  
                  <p className="text-xs text-muted-foreground">
                    💡 将生成约 <span className="font-semibold text-primary">{getEstimatedSegments()}</span> 个片段
                  </p>
                </div>
              )}

              {splitMode === 'segments' && (
                <div className="space-y-2">
                  <div className="flex justify-between">
                    <Label className="text-sm">分割段数</Label>
                    <span className="text-sm text-muted-foreground">{segmentCount} 段</span>
                  </div>
                  <Slider
                    value={[segmentCount]}
                    onValueChange={([v]) => setSegmentCount(v)}
                    min={2}
                    max={100}
                    step={1}
                  />
                  <p className="text-xs text-muted-foreground">
                    每段约 {formatTime(audioFile.duration / segmentCount)}
                  </p>
                </div>
              )}

              {splitMode === 'silence' && (
                <>
                  <div className="space-y-2">
                    <div className="flex justify-between">
                      <Label className="text-sm">静音阈值（dB）</Label>
                      <span className="text-sm text-muted-foreground">{silenceThreshold} dB</span>
                    </div>
                    <Slider
                      value={[Math.abs(silenceThreshold)]}
                      onValueChange={([v]) => setSilenceThreshold(-v)}
                      min={20}
                      max={60}
                      step={1}
                    />
                  </div>

                  <div className="space-y-2">
                    <div className="flex justify-between">
                      <Label className="text-sm">最小静音时长（秒）</Label>
                      <span className="text-sm text-muted-foreground">{minSilenceDuration} 秒</span>
                    </div>
                    <Slider
                      value={[minSilenceDuration]}
                      onValueChange={([v]) => setMinSilenceDuration(v)}
                      min={0.5}
                      max={5}
                      step={0.5}
                    />
                  </div>
                </>
              )}
            </div>

            {/* 输出设置 */}
            <div className="space-y-4 p-4 bg-muted/30 rounded-lg">
              <Label className="text-sm font-semibold">输出设置</Label>
              
              {/* 输出文件夹 */}
              <div className="space-y-2">
                <Label className="text-sm">输出文件夹</Label>
                <div className="flex gap-2">
                  <div className="flex-1 px-3 py-2 bg-background border border-input rounded-md text-sm overflow-hidden">
                    {outputFolder ? (
                      <span className="block truncate" title={outputFolder}>
                        {outputFolder}
                      </span>
                    ) : (
                      <span className="text-muted-foreground">未选择输出文件夹</span>
                    )}
                  </div>
                  <Button
                    onClick={selectOutputFolder}
                    variant="outline"
                    size="sm"
                  >
                    <FolderOpen className="mr-2 h-4 w-4" />
                    浏览
                  </Button>
                </div>
                {outputFolder && (
                  <p className="text-xs text-muted-foreground">
                    💡 已自动保存，下次打开会记住此路径
                  </p>
                )}
              </div>
              
              <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                <div className="space-y-2">
                  <Label className="text-sm">输出格式</Label>
                  <Select value={outputFormat} onValueChange={setOutputFormat}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="mp3">MP3</SelectItem>
                      <SelectItem value="wav">WAV</SelectItem>
                      <SelectItem value="m4a">M4A</SelectItem>
                      <SelectItem value="aac">AAC</SelectItem>
                      <SelectItem value="ogg">OGG</SelectItem>
                    </SelectContent>
                  </Select>
                </div>

                <div className="space-y-2">
                  <Label className="text-sm">音质</Label>
                  <Select value={outputQuality} onValueChange={setOutputQuality}>
                    <SelectTrigger>
                      <SelectValue />
                    </SelectTrigger>
                    <SelectContent>
                      <SelectItem value="low">低 (64kbps)</SelectItem>
                      <SelectItem value="medium">中 (128kbps)</SelectItem>
                      <SelectItem value="high">高 (192kbps)</SelectItem>
                      <SelectItem value="veryhigh">极高 (320kbps)</SelectItem>
                    </SelectContent>
                  </Select>
                </div>
              </div>

              <div className="space-y-2">
                <Label className="text-sm">文件名前缀</Label>
                <Input
                  value={filenamePrefix}
                  onChange={(e) => setFilenamePrefix(e.target.value)}
                  placeholder="segment"
                />
                <p className="text-xs text-muted-foreground">
                  示例: {filenamePrefix}_001.{outputFormat}
                </p>
              </div>

              <div className="flex items-center justify-between">
                <Label className="text-sm">添加时间戳</Label>
                <Switch checked={addTimestamp} onCheckedChange={setAddTimestamp} />
              </div>
            </div>

            {/* 开始分割按钮 */}
            <div className="space-y-2">
              <Button
                onClick={handleSplit}
                className="w-full"
                disabled={isProcessing || !outputFolder}
              >
                {isProcessing ? (
                  <>
                    <Loader2 className="mr-2 h-4 w-4 animate-spin" />
                    分割中... {progress}%
                  </>
                ) : (
                  <>
                    <Scissors className="mr-2 h-4 w-4" />
                    开始分割
                  </>
                )}
              </Button>
              
              {!outputFolder && (
                <p className="text-xs text-center text-orange-500">
                  ⚠️ 请先选择输出文件夹
                </p>
              )}
            </div>

            {/* 处理进度条 */}
            {isProcessing && (
              <div className="space-y-2">
                <div className="w-full bg-secondary rounded-full h-2.5 overflow-hidden">
                  <div 
                    className="bg-primary h-2.5 rounded-full transition-all duration-300"
                    style={{ width: `${progress}%` }}
                  />
                </div>
                <p className="text-xs text-center text-muted-foreground">
                  {totalSegments !== null && totalSegments > 0 && currentSegment > 0 ? (
                    <>正在处理第 {currentSegment} / {totalSegments} 个片段...</>
                  ) : (
                    <>正在处理中... {progress}%</>
                  )}
                </p>
              </div>
            )}
          </CardContent>
        </Card>
      )}

      {/* 分割结果 */}
      {splitResults.length > 0 && (
        <Card data-split-results>
          <CardHeader>
            <div className="flex items-center justify-between">
              <div>
                <CardTitle className="text-base flex items-center gap-2">
                  <CheckCircle2 className="h-5 w-5 text-green-500" />
                  分割完成
                </CardTitle>
                <CardDescription>共生成 {splitResults.length} 个音频片段</CardDescription>
              </div>
              <Button variant="outline" size="sm" onClick={openOutputFolder}>
                <Download className="mr-2 h-4 w-4" />
                打开文件夹
              </Button>
            </div>
          </CardHeader>
          <CardContent>
            <div className="space-y-2">
              {splitResults.map((result, index) => (
                <div
                  key={index}
                  className="flex items-center justify-between p-3 border rounded-lg hover:bg-muted/50 transition-colors"
                >
                  <div className="flex items-center gap-3 flex-1 min-w-0">
                    <FileAudio className="h-4 w-4 text-muted-foreground flex-shrink-0" />
                    <div className="flex-1 min-w-0">
                      <p className="text-sm font-medium truncate">{result.name}</p>
                      <p className="text-xs text-muted-foreground">
                        {formatTime(result.duration)} · {formatSize(result.size)}
                      </p>
                    </div>
                  </div>
                  <Button 
                    variant="ghost" 
                    size="icon"
                    onClick={() => playSegment(result.path)}
                    className={playingSegmentPath === result.path && isPlaying ? 'text-primary' : ''}
                  >
                    {playingSegmentPath === result.path && isPlaying ? (
                      <Pause className="h-4 w-4" />
                    ) : (
                      <Play className="h-4 w-4" />
                    )}
                  </Button>
                </div>
              ))}
            </div>
          </CardContent>
        </Card>
      )}

      {/* 未选择文件时的提示 */}
      {!audioFile && (
        <Card className="p-12">
          <div className="text-center text-muted-foreground space-y-2">
            <Scissors className="h-12 w-12 mx-auto mb-4 opacity-50" />
            <p className="text-lg">请选择一个音频文件开始分割</p>
            <p className="text-sm">支持 MP3、WAV、M4A、AAC、OGG 等常见音频格式</p>
          </div>
        </Card>
      )}
    </div>
  )
}

